

//
//  CPJHomePageViewModel.swift
//  Sina
//
//  Created by YYY on 2017/8/8.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit
import SDWebImage

private let max_pullUpTimes = 3

class CPJHomePageViewModel: NSObject {

    //数组保存model对象数据
    lazy var statusList = [CPJListViewModel]()
    
    private var pullUpErrorTimes = 0
    func loadStatus(pullUP: Bool = false,completion: @escaping (_ isSuccess: Bool,_ shouldRefresh: Bool)->())
    {
        if pullUP && pullUpErrorTimes > max_pullUpTimes
        {
            completion(true,false)
            return
        }
        
        let sinceID = pullUP ? 0 : (statusList.first?.homePageModel.id ?? 0)
        let max_id = pullUP ? (statusList.last?.homePageModel.id ?? 0) : 0
        
        CPJWeiboListDAL.loadStatus(since_id: sinceID, max_id: max_id) { (listArray, isOK) in
            
//        }
//        
//        CPJNetworkManager.shared.statusList(since_id: sinceID,max_id: max_id) { (listArray, isOK) in
            //如果网络请求失败，直接返回回调
            if !isOK
            {
                completion(false,false)
                return
            }
            
            //视图模型
            var array = [CPJListViewModel]()
            for dict in listArray ?? []
            {
                
                //创建首页模型
                let model = CPJHomePageModel()
                //使用字典设置模型数值
                model.yy_modelSet(with: dict)
                //使用模型创建视图模型
                let viewModel = CPJListViewModel(model: model)
                array.append(viewModel)
            }
            //视图模型创建完成 array
            
            if pullUP
            {
                //加载更多
                self.statusList += array
            }
            else
            {
                //刷新数据
                self.statusList = array + self.statusList
            }
            
            if array.count==0 && pullUP
            {
                self.pullUpErrorTimes += 1
                completion(isOK,false)
            }
            else
            {
                //真正完成数据的回调
                //缓存单张图片
                self.cacheSinglePictureUrl(listArray: array,finished: completion)
            }
        }
    }
    
    //缓存单张图片URL地址
    private func cacheSinglePictureUrl(listArray: [CPJListViewModel],finished: @escaping (_ isSuccess: Bool,_ shouldRefresh: Bool)->())
    {
        //记录数据长度
        var length = 0
        
        //调度组
        let group = DispatchGroup()
        
        for vm in listArray
        {
            if vm.picture_urls?.count != 1
            {
                continue
            }
            guard let urlString = vm.picture_urls?[0].thumbnail_pic,
                let url = URL(string: urlString) else
            {
                continue
            }
            
            //缓存图像
            
            // downloadImage 是SDWebImage的核心方法
            // 图像下载完成之后，会自动保存到沙盒中，文件路径是URL的md5
            // 如果沙盒已经存在缓存的图像，直接使用本地缓存图像
            // 不会发起网路请求，同时回调方法，正常执行
            // 减少流量的使用
            
            //入组
            group.enter()
            //SDWebImageManager.shared().loadImage(with: <#T##URL?#>, options: <#T##SDWebImageOptions#>, progress: <#T##SDWebImageDownloaderProgressBlock?##SDWebImageDownloaderProgressBlock?##(Int, Int, URL?) -> Void#>, completed: <#T##SDInternalCompletionBlock?##SDInternalCompletionBlock?##(UIImage?, Data?, Error?, SDImageCacheType, Bool, URL?) -> Void#>)
            SDWebImageDownloader.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _) in
                
                //将图像转换成二进制数据
                if let tempImage = image,
                    let data = UIImagePNGRepresentation(tempImage)
                {
                    length += data.count
                    //更新配图视图单张图片的大小
                    vm.updateSingleImageSize(image: tempImage)
                }
                
                //出组
                group.leave()
               
            })
        }
        
        //监听
        group.notify(queue: DispatchQueue.main) {
       
            finished(true,true)
        }
    }
}
